/**
 * 2025/01/01 - 2025/12/31
 */
package com.snail.server.iam.menu.manager;

import com.snail.server.iam.app.entity.App;
import com.snail.server.iam.app.service.AppService;
import com.snail.server.iam.menu.entity.Menu;
import com.snail.server.iam.menu.mapping.MenuMapping;
import com.snail.server.iam.menu.service.MenuService;
import com.snail.server.iam.menu.vo.AppMenuVO;
import com.snail.server.iam.menu.vo.MenuVO;
import com.snail.server.iam.user.entity.UserAppMapping;
import com.snail.server.iam.user.service.UserService;
import com.snail.starter.commons.threadlocal.UserContext;
import com.snail.starter.commons.threadlocal.UserContextUtils;
import com.snail.starter.utils.tree.TreeUtil;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author zgadmin
 * @date 2025/9/26 18:01
 */
@Component
public class MenuManager {

    @Resource
    MenuService menuService;

    @Resource
    AppService appService;

    @Resource
    UserService userService;

    @Resource
    MenuMapping menuMapping;

    public AppMenuVO menuByApp(Long appId) {
        UserContext userContext = UserContextUtils.get();
        App app = appService.checkApp(appId);
        UserAppMapping userApp = userService.checkUserTenant(userContext.getTenantId(), userContext.getUserId(), app.getAppId());
        List<Menu> menus = menuService.list(userApp.getAppId());
        return AppMenuVO.of(app.getAppId(),
                TreeUtil.buildTree(menus, Menu::getParentId,
                        menu -> menuMapping.toMenuVO(menu), Menu::getMenuId,
                        MenuVO::setChildren, MenuVO::getOrderBy));
    }

}